import { Component,OnInit,Inject } from '@angular/core';
import { MatDialog,MatDialogRef,MAT_DIALOG_DATA } from '@angular/material/dialog';

import { HmiService } from './../../_services/hmi.service';
import { HttpClient } from '@angular/common/http';
import { TagPropertyComponent } from './../../device/tag-property/tag-property.component';
import { Device, DeviceNetProperty,Tag,TAG_PREFIX, DeviceType  } from './../../_models/device';
import { Node, NodeType } from './../../gui-helpers/treetable/treetable.component';
import { ProjectService } from './../../_services/project.service';
import { GaugeSettings } from './../../_models/hmi';
// import { DeviceTagDialog } from './../../device/device.component';
import { Utils } from './../../_helpers/utils';


@Component({
    selector: 'app-measure-property',
    templateUrl: './measure-property.component.html',
    styleUrls: ['./measure-property.component.css']
})
export class MeasurePropertyComponent implements OnInit {

    constructor(
        private projectService: ProjectService,
        private dialog: MatDialog,
        private hmiService: HmiService,
        public dialogRef: MatDialogRef<MeasurePropertyComponent>,
        private http: HttpClient,
        @Inject(MAT_DIALOG_DATA) public data: any
        ) {
        console.log(data);
        const { variableId,...prop}=data;
        this.variableId=variableId;
        this.data=prop;
    }

    settings: GaugeSettings;

    deviceMeasureList: any[]=[];
    form: any={};
    deviceSelected: Device = null;
    devices: any;
    deviceList: Device[];
    dirty = false;

    tagsMap = {};

    url='';
    addUrl=true;
    jsonParam: string;
    kafkaName: string;
    host: string;
    topic: string;
    measureCode: string;
    deviceId: string;
    polling: number;

    sameDevice=false;
    variableId: string;

    ngOnInit() {

        this.deviceList = this.data.devices;
        if(this.variableId){
            const device=this.projectService.getDeviceFromTagId(this.variableId);
            if(device && device.property){
                this.polling=device.polling;
                if(device.property.jsonParam){
                    this.deviceId=device.property.jsonParam.deviceId;
                    this.getMeasureList(this.deviceId);
                    this.measureCode=device.property.jsonParam.keyword;
                }
            }
        }

    }

    getMeasureList(deviceId){
        console.log(deviceId);
        if(deviceId){
            this.http.post('/deviceApi/device/mgt/processedDeviceMeasureListPage',{current:1,size:100,deviceId}).subscribe((res: any) => {
                if(res.code===200){
                    this.deviceMeasureList=res.data.list;
                }
            });
        }else{
            this.deviceMeasureList=[];
        }
    }

    // setVariable(tag: Tag) {
    //     console.log('设置tag变量id',tag);
    //     if (tag) {
    //         this.variableId = tag.id;
    //     } else {
    //         this.variableId = null;
    //     }
    //     this.onChanged();
    // }


    onMeasure(){
        console.log(this.deviceId,this.measureCode,this.polling);
        let deviceId=this.deviceId+':'+this.measureCode;
        let device = this.projectService.getDeviceFromId(deviceId);
        console.log(device);
        if(!device){
            this.sameDevice=false;
            // 添加设备时，应该用设备id作为主键
            device = new Device(deviceId);
            // 此处没有设备名称
            device.name=this.deviceId+':'+this.deviceMeasureList.find(dm=>dm.code===this.measureCode).name;
            device.property = new DeviceNetProperty();
            device.property.address='https://iot-device-service-1.dev.ennew.com/device/measureDefinitionListPage';
            device.property.jsonParam={
                keyword:this.measureCode,
                current:1,
                size:10,
                deviceId:this.deviceId,
                dataQueryFlag:true
            };
            device.property.method='POST';
            device.polling=(this.polling || 3)*1000;
            device.enabled = false;
            device.tags = {};
        }else{
            this.sameDevice=true;
            this.tagsMap=device.tags;
        }
        device.type = 'WebAPI';
        device.enabled = true;
        this.editDevice(device);
    }


    onMeasureCodeChange(measureCode){
        this.measureCode=measureCode;
    }

    onShowTag(){
        let deviceId=this.url.lastIndexOf('/')>-1?this.url.substring(this.url.lastIndexOf('/')+1):'';
        let index = this.deviceList.findIndex(d=>d.id===deviceId);
        if(index>-1){
            const device=this.deviceList[index];
            this.editDevice(device);
        }else{
            if(!deviceId){
                deviceId=JSON.parse(this.jsonParam).deviceId;
            }
            this.addDevice(deviceId);
        }
        // // 这里调用接口，订阅
        // if(this.addUrl){
        //     this.addDevice();
        // }else{
        //     console.log(this.bindDeviceId,this.devices);
        //     const device=this.devices[this.bindDeviceId];
        //     this.editDevice(device);
        // }

    }

    onUrlChange(url){
        this.url=url;
        let deviceId=url.lastIndexOf('/')>-1?url.substring(url.lastIndexOf('/')+1):'';
        this.deviceSelected=this.projectService.getDeviceFromId(deviceId);
        this.tagsMap=this.deviceSelected.tags;
    }

    addDevice(newId){
        // 添加设备时，应该用设备id作为主键
        let device = new Device(newId);
        // 此处没有设备名称
        device.name=newId;
        device.property = new DeviceNetProperty();
        device.property.address=this.url;
        device.property.jsonParam=this.jsonParam;
        device.polling=(this.polling || 3)*1000;
        device.enabled = false;
        device.tags = {};
        this.editDevice(device);

    }

    editDevice(device){
        let olddevice = JSON.parse(JSON.stringify(device));
        let tempdevice = JSON.parse(JSON.stringify(device));
        // if (this.appService.isClientApp || this.appService.isDemoApp) {
        //     delete device.property;
        // }
        if (device.property && tempdevice.property) {
            device.property.address = tempdevice.property.address;
            device.property.port = parseInt(tempdevice.property.port);
            device.property.slot = parseInt(tempdevice.property.slot);
            device.property.rack = parseInt(tempdevice.property.rack);
            device.property.slaveid = tempdevice.property.slaveid;
            device.property.baudrate = tempdevice.property.baudrate;
            device.property.databits = tempdevice.property.databits;
            device.property.stopbits = tempdevice.property.stopbits;
            device.property.parity = tempdevice.property.parity;
            device.property.options = tempdevice.property.options;
            device.property.method = tempdevice.property.method || 'GET';
            device.property.format = tempdevice.property.format;
            device.property.broadcastAddress = tempdevice.property.broadcastAddress;
            device.property.adpuTimeout = tempdevice.property.adpuTimeout;
            if (tempdevice.property.connectionOption) {
                device.property.connectionOption = tempdevice.property.connectionOption;
            }
        }
        this.projectService.setDevice(device, olddevice, null);

        this.deviceSelected=device;
        this.addOpcTags(null);
        console.log(this.deviceSelected,device);
        // this.showMode = DeviceViewModeType.tags;
        // this.deviceList.updateDeviceValue();
        // this.deviceList.setSelectedDevice(device);
    }

    addOpcTags(tag: Tag) {

        console.log('点击我',this.deviceSelected, tag, this.devices );
        this.hmiService.onDeviceWebApiRequest.subscribe(res => {
            console.log('这里才是webapi',res);
            if (res.result) {
                this.form.variableDefaultProp=res.result;
                // 目前一个测点仅有一个量测值，若测点相同，表示量测值相同
                if(this.sameDevice){
                    this.form.variableId=Object.keys(this.deviceSelected.tags)[0];
                    this.dialogRef.close(this.form);
                    return;
                }
                console.log(res.result,typeof res.result.metricValue);
                let tag = new Tag(Utils.getGUID(TAG_PREFIX));
                tag.name = 'metricValue';
                tag.label = 'metricValue';
                tag.type = typeof res.result.metricValue;
                tag.address =  'metricValue';
                console.log(tag,this.deviceSelected);
                this.checkToAdd(tag, this.deviceSelected);
                this.projectService.setDeviceTags(this.deviceSelected);
            }
        });
        this.hmiService.askWebApiProperty(this.deviceSelected.property);
        return;
        /** 以下为弹窗格式 */
        let dialogRef = this.dialog.open(TagPropertyComponent, {
            panelClass: 'dialog-property',
            data: { device: this.deviceSelected, tag: tag, devices: this.devices },
            position: { top: '60px' }
        });
        dialogRef.afterClosed().subscribe(result => {
            console.log(result);
            if (result) {
                let tagId='';
                if(result.nodes.length===1){
                    tagId=Utils.getGUID(TAG_PREFIX);
                }
                this.dirty = true;
                if (this.deviceSelected.type === DeviceType.WebAPI) {
                    // this.clearTags();
                }
                result.nodes.forEach((n: Node) => {
                    // 添加订阅时应以图形id作为主键
                    let tag = new Tag(tagId?tagId:Utils.getGUID(TAG_PREFIX));
                    tag.name = n.text;
                    tag.label = n.text;
                    tag.type = n.type;
                    if (this.deviceSelected.type === DeviceType.BACnet) {
                        tag.label = n.text;
                        tag.memaddress = n.parent?.id;
                    } else if (this.deviceSelected.type === DeviceType.WebAPI) {
                        tag.label = n.text;
                        if (n.class === NodeType.Reference) {
                            tag.memaddress = n.property;        // in memaddress save the address of the value
                            tag.options = n.todefine;           // save the id and value in text to set by select list
                            tag.type = n.type;
                        }
                    }
                    tag.address = n.id;
                    console.log(tag,result.device);
                    this.checkToAdd(tag, result.device);
                });
                console.log(this.deviceSelected);
                this.projectService.setDeviceTags(this.deviceSelected);
                console.log(this.tagsMap);
                if(result.nodes.length>1){
                    alert('您本次订阅多个属性，无法为您自动绑定主题！请点击“选择订阅按钮”绑定主题');
                }else{
                    this.variableId = tagId;
                    this.deviceList=this.data.devices;
                }
            }

        });
    }

    checkToAdd(tag: Tag, device: Device, overwrite: boolean = false) {
        let exist = false;
        Object.keys(device.tags).forEach((key) => {
            console.log(device.tags[key]);
            if (device.tags[key].id) {
                if (device.tags[key].id === tag.id) {
                    exist = true;
                }
            } else if (device.tags[key].name === tag.name) {
                console.log('111');
                exist = true;
            }
        });
        // console.log(device.tags,tag,exist);
        if (!exist || overwrite) {
            // 说明已经订阅过，需要用之前的tagid,仅保留一个
            device.tags[tag.id] = tag;
        }

        this.tagsMap[tag.id] = tag;
        this.variableId=tag.id;
        this.deviceSelected.tags=this.tagsMap;
        console.log(tag,this.deviceSelected.tags);
        this.bindToTable(this.deviceSelected.tags);
    }

    private bindToTable(tags) {
        console.log(tags);
        if (!tags) {
            tags = {};
        }
        let arr=[];
        Object.values(tags).forEach((item: any)=>{
            arr.push({...item,value:typeof(item.value)==='object'?JSON.stringify(item.value):item.value});
        });
        console.log(',,,,,,,,',Object.keys(tags));
        this.hmiService.tagsSubscribe(Object.keys(tags));
        console.log(this.projectService.getDevices(),this.variableId);
        this.form.variableId=this.variableId;
        this.dialogRef.close(this.form);

    }


    onOkClick(){
        this.onMeasure();
    }


    onNoClick(){
        this.dialogRef.close();
    }
}
